#pragma once
#include <iostream>
#include <pthread.h>
#include <string>
#include <queue>

const static int defaultcap = 5;

template<class T>
class BlockQueue
{
public:
    BlockQueue(int cap = defaultcap)
    :   _max_cap(cap)
    {
        pthread_mutex_init(&_mutex,nullptr);
        _p_cond = PTHREAD_COND_INITIALIZER;
        _c_cond = PTHREAD_COND_INITIALIZER;
    }

    bool IsEmpty()
    {
        return _blockqueue.size() == 0;
    }

    bool IsFull()
    {
        return _blockqueue.size() == _max_cap;
    }

    void Pop(T* out)
    {
        pthread_mutex_lock(&_mutex);
        //while可以防止伪唤醒
        while(IsEmpty())
        {
            pthread_cond_wait(&_c_cond,&_mutex);
        }
        *out = _blockqueue.front();
        _blockqueue.pop();
        pthread_mutex_unlock(&_mutex);
        pthread_cond_signal(&_p_cond);
    }

    void Push(const T& in)
    {
        pthread_mutex_lock(&_mutex);
        while(IsFull())
        {
            pthread_cond_wait(&_c_cond,&_mutex);
        }
        _blockqueue.push(in);
        pthread_mutex_unlock(&_mutex);
        pthread_cond_signal(&_c_cond);
    }
    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_p_cond);
        pthread_cond_destroy(&_c_cond);
    }
private:    
    std::queue<T> _blockqueue;
    int _max_cap;
    pthread_mutex_t _mutex;
    pthread_cond_t _p_cond; //producer
    pthread_cond_t _c_cond; //consumer
};